<?php

/**
 * Doctrine ACL model adapter
 *
 * @author     Mon Zafra <monzee at gmail>
 * @copyright  (c)2009 Mon Zafra
 * @category   Mz
 * @package    modules
 * @subpackage admin
 * @license    http://mz-project.googlecode.com/svn/trunk/LICENSE    MIT License
 * @version    SVN: $Id: Doctrine.php 47 2009-05-28 17:56:56Z monzee $
 */
class Admin_Model_Acl_Doctrine implements Admin_Model_Acl_Adapter
{
    protected $_roles = array();

    public function getRoleById($roleId)
    {
        if (!isset($this->_roles[$roleId])) {
            $q = Doctrine_Query::create();
            $q->from('Admin_Model_Doctrine_Role r')
              ->leftJoin('r.Parents p')
              ->select('r.id, p.id')
              ->where('r.id = ?', $roleId);
            $this->_roles[$roleId] = $q->fetchOne(null, Doctrine::HYDRATE_ARRAY);
        }
        return $this->_roles[$roleId];
    }

    public function getParentRoles($role)
    {
        return $role['Parents'];
    }

    public function getRulesByResourceId($resId)
    {
        $q = Doctrine_Query::create();
        $q->from('Admin_Model_Doctrine_Permission p')
          ->select('p.resource_id, p.privilege, p.role_id, p.allowed')
          ->where('p.resource_id = ?', $resId);
        return $q->fetchArray();
    }

    public function getUserByUsername($username)
    {
        $q = Doctrine_Query::create();
        $q->from('Admin_Model_Doctrine_User u')
          ->leftJoin('u.Roles r')
          ->leftJoin('r.Parents p')
          ->select('u.id, u.username, r.id, p.id')
          ->where('u.username = ?', $username);
        $res = $q->fetchOne(null, Doctrine::HYDRATE_ARRAY);
        foreach ($res['Roles'] as $role) {
            $this->_roles[$role['id']] = $role;
        }
        return $res;
    }

    public function getUserRoles($user)
    {
        return $user['Roles'];
    }

    /*
     * the next 3 functions are not part of the interface and are just used
     * for testing
     */

    public function getAllUsers()
    {
        $q = Doctrine_Query::create()
                           ->from('Admin_Model_Doctrine_User u')
                           ->leftJoin('u.Roles r')
                           ->select('u.id, u.username, r.id');
        return $q->fetchArray();
    }

    public function getAllRoles()
    {
        $q = Doctrine_Query::create()
                           ->from('Admin_Model_Doctrine_Role r')
                           ->leftJoin('r.Parents p')
                           ->select('r.id, p.id');
        return $q->fetchArray();
    }

    public function getAllPermissions()
    {
        $q = Doctrine_Query::create()->from('Admin_Model_Doctrine_Permission');
        return $q->fetchArray();
    }


}